from flask import Blueprint, request, jsonify, send_file
from models.base import db
from models import Employee, ResumeTemplate
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os
import openpyxl
from openpyxl.utils import get_column_letter
from io import BytesIO
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from datetime import datetime, date
from routes.certificate import get_common_styles, adjust_column_width

export_bp = Blueprint('export', __name__)

@export_bp.route('/api/employees/<int:employee_id>/export/<int:template_id>', methods=['GET'])
def export_resume(employee_id, template_id):
    try:
        employee = Employee.query.get(employee_id)
        if not employee:
            return jsonify({'error': '员工不存在'}), 404
        template = ResumeTemplate.query.get(template_id)
        if not template:
            return jsonify({'error': '模板不存在'}), 404
        doc = Document()
        title = doc.add_heading(f'{employee.name}的简历', 0)
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER
        doc.add_heading('基本信息', level=1)
        basic_info = doc.add_paragraph()
        basic_info.add_run(f'姓名：{employee.name}\n')
        basic_info.add_run(f'性别：{employee.gender}\n')
        basic_info.add_run(f'出生日期：{employee.birth_date}\n')
        basic_info.add_run(f'联系电话：{employee.phone}\n')
        basic_info.add_run(f'邮箱：{employee.email}\n')
        basic_info.add_run(f'毕业院校：{employee.school}\n')
        basic_info.add_run(f'学历：{employee.degree}\n')
        if employee.work_experiences:
            doc.add_heading('工作经历', level=1)
            for exp in employee.work_experiences:
                exp_para = doc.add_paragraph()
                exp_para.add_run(f'{exp.company} | {exp.position}\n')
                exp_para.add_run(f'{exp.start_date} - {exp.end_date}\n')
                exp_para.add_run(f'部门：{exp.description}\n')
                exp_para.add_run(f'主要职责：{getattr(exp, "responsibilities", "")}\n')
                exp_para.add_run(f'工作成果：{getattr(exp, "achievements", "")}\n')
        if employee.projects:
            doc.add_heading('项目经验', level=1)
            for project in employee.projects:
                project_para = doc.add_paragraph()
                project_para.add_run(f'{project.name} | {project.client_name} | {project.role}\n')
                project_para.add_run(f'{project.start_date} - {project.end_date}\n')
                project_para.add_run(f'项目描述：{project.description}\n')
                project_para.add_run(f'主要职责：{project.responsibilities}\n')
                project_para.add_run(f'项目成果：{project.achievements}\n')
        if employee.skills:
            doc.add_heading('技能证书', level=1)
            skill_para = doc.add_paragraph()
            skill_para.add_run(employee.skills)
        filename = f'resume_{employee.name}.docx'
        doc.save(filename)
        return send_file(
            filename,
            as_attachment=True,
            download_name=filename,
            mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        )
    except Exception as e:
        return jsonify({'error': str(e)}), 500
    finally:
        if os.path.exists(filename):
            os.remove(filename)

@export_bp.route('/api/employees/export/excel', methods=['GET'])
def export_employees_excel():
    try:
        employees = Employee.query.all()
        # 导出所有简历基本信息字段，排除id、created_at、updated_at
        fields = [
            ('name', '姓名'),
            ('number', '工号'),
            ('entry_time', '入职时间'),
            ('department', '部门'),
            ('gender', '性别'),
            ('birth_date', '出生日期'),
            ('ethnicity', '民族'),
            ('native_place', '籍贯'),
            ('birth_place', '出生地'),
            ('political_status', '政治面貌'),
            ('marital_status', '婚姻状况'),
            ('health_status', '健康状况'),
            ('phone', '联系电话'),
            ('email', '电子邮箱'),
            ('school', '毕业院校'),
            ('major', '专业'),
            ('degree', '学历'),
            ('academic_degree', '学位'),
            ('graduation_date', '毕业时间'),
            ('language_level', '语言水平'),
            ('title', '职称'),
            ('position_start_date', '现岗位起始时间'),
            ('current_company', '现工作单位'),
            ('position', '现任职务'),
            ('contract_period_start', '合同起始日期'),
            ('contract_period_end', '合同结束日期'),
            ('current_address', '现住址'),
            ('id_number', '身份证号'),
            ('household_address', '户口地址'),
            ('emergency_contact', '紧急联系人'),
            ('emergency_phone', '紧急联系电话'),
            ('awards', '获奖情况'),
            ('skills', '专业技能'),
        ]
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = '员工简历列表'
        # 获取通用样式
        header_style, _ = get_common_styles()
        # 表头样式（绿色#91C36A，白色加粗12px，居中，24px高，灰色细边框）
        header_font = Font(bold=True, color='FFFFFF', size=12, name='微软雅黑')
        header_fill = PatternFill('solid', fgColor='91C36A')
        center_alignment = Alignment(horizontal='center', vertical='center')
        thin_gray_border = Border(
            left=Side(style='thin', color='CCCCCC'),
            right=Side(style='thin', color='CCCCCC'),
            top=Side(style='thin', color='CCCCCC'),
            bottom=Side(style='thin', color='CCCCCC')
        )
        # 写入表头
        for col, (_, header) in enumerate(fields, 1):
            cell = ws.cell(row=1, column=col, value=header)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = center_alignment
            cell.border = thin_gray_border
            ws.row_dimensions[1].height = 24
        # 内容样式（宋体11px，左对齐，14px高，白底，灰色细边框）
        content_font = Font(name='宋体', size=11, color='000000')
        left_alignment = Alignment(horizontal='left', vertical='center')
        for row, emp in enumerate(employees, 2):
            for col, (field, _) in enumerate(fields, 1):
                value = getattr(emp, field, '')
                # 确保值是字符串类型，特别是对于新增加的字段
                if value is None:
                    value = ''
                elif field == 'language_level':
                    # 特别处理language_level，如果是列表则转为字符串，否则保持原样或转为空字符串
                    if isinstance(value, list):
                        value = ', '.join([str(v) for v in value if v is not None])
                    else:
                         value = str(value) if value is not None else ''
                elif isinstance(value, (datetime, date)):
                    value = value.strftime('%Y-%m-%d')
                else:
                    value = str(value)
                
                # 添加日志输出，用于调试
                # print(f"Exporting emp_id: {emp.id}, field: {field}, value: {value}")

                cell = ws.cell(row=row, column=col, value=value)
                cell.font = content_font
                cell.alignment = left_alignment
                cell.border = thin_gray_border
                cell.fill = PatternFill('solid', fgColor='FFFFFF')
                ws.row_dimensions[row].height = 14
        # 自动列宽
        adjust_column_width(ws, employees)
        
        output = BytesIO()
        wb.save(output)
        output.seek(0)

        # print(f"Export successful, file size: {output.getbuffer().nbytes}") # 添加成功日志

        return send_file(
            output,
            as_attachment=True,
            download_name='员工简历列表.xlsx',
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
    except Exception as e:
        # 打印详细的错误信息
        # print(f"An error occurred during Excel export: {e}")
        # import traceback
        # traceback.print_exc()
        return jsonify({'error': f'导出失败: {str(e)}'}), 500 